package com.shangxian.giveithome.test;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

/**
 * @author coderFu
 * @create 2021/5/2
 */
public class Qrtest2 {
    public static void main(String[] args) {
        try {
            BufferedImage img = createQrImg("https://www.baidu.com", 400, 400);

            File codeImgFile = new File("C://test", "000");

            ImageIO.write(img, "png", codeImgFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    public static BufferedImage createQrImg(String content, Integer width, Integer height) throws Exception
    {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        // 生成矩阵信息
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        // 遍历矩阵，获取矩阵中黑点开始的位置
        int matrixWidth = bitMatrix.getWidth();
        int matrixHeight = bitMatrix.getHeight();
        Integer startX = null;
        Integer startY = null;
        for (int x = 0; x < matrixWidth; x++)
        {
            if(null!=startX){
                break;
            }
            for (int y = 0; y < matrixHeight; y++)
            {
                if (bitMatrix.get(x, y))
                {
                    // 如果有黑点，临时记录下来
                    startX = x;
                    startY = y;
                    break;
                }
            }
        }
        // 将矩阵信息转为图片信息（宽 和 高 要减去 两边 空白区的长度）
        BufferedImage image = new BufferedImage(width-2*startX, height-2*startY, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, width, height);
        graphics.setColor(Color.BLACK);
        for (int x = startX; x < matrixWidth-startX; x++)
        {
            for (int y = startY; y < matrixHeight-startY; y++)
            {
                if (bitMatrix.get(x, y))
                {
                    // 如果有黑点，则画到图上去（从图上的0点开始画起）
                    graphics.fillRect(x-startX , y-startY, 1, 1);
                }
            }
        }
        image.flush();
        return image;
    }

}
